const http = require("../../../utils/request");
const areaList = require("../../../utils/moudle/ChineseAdministrativeRegion").data;
const pageTitleList = ["基础信息", "新增公司"]
const feedback=require("../../../utils/feedback")

Page({
  data: {
    isdelete: false,
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    //页面状态 0:基础信息，1:新增公司
    pageState: 0,
    isEdit: false,
    //页面标题
    pageTitle: "",
    //输入框
    inputConfig: {
      companyName: "公司名称",
      contacts: "联系人  ",
      phone: "联系电话",
      // TODO:选择框
      address: "联系地址",
      introduction: "简介",
      pictures: "照片"
    },
    phoneStatus: 'success',
    phoneErrorInfo: "",
    companyDetail: {},
    farmsDetail: [],
    //上传图片
    uploadPictureFiles: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    // 弹出层
    popupVisible: false,
    popupFarmsIndex: null,
    popupFarmsDetail: {},
    farmsDetailTitle: {
      farmName: "农场名字",
      supplyFarmAddress: "农场地址"
    },
    //地址选择
    cascaderValue: '',
    cascaderCellNote: "请输入地址",
    cascaderVisible: false,
    areaList: areaList,
  },

  /**
   * @public
   */
  tapCancel() {
    if (this.data.isEdit && this.data.pageState == 0) {
      this.initPageData(this.data.companyDetail.id).then(() => {
        this.setData({
          isEdit: false
        })
      })
    } else {
      wx.navigateBack(2)
    }
  },

  /**
   * @public 按钮为编辑则切换状态，为确定则校验信息并post/put公司信息
   */
  tapConfirmOrEdit() {
    if (this.data.isEdit == false) //按钮为编辑
    {
      this.changePageState()
    } else {
      feedback.showLoading()
      this.data.farmsDetail&&this.dealFarmsDetail()
      if (!this.isEmptyCompanyDetail(this.data.companyDetail)) {
        if (this.data.pageState == 0) {
          this.putCompanyDetail(this.data.companyDetail, this.data.farmsDetail)
        } else if (this.data.pageState == 1) {
          this.postCompanyDetail(this.data.companyDetail, this.data.farmsDetail)
        }
        this.changePageState()
      }
    }
  },
  /**
   * 修改农场信息，删除农场
   */
  dealFarmsDetail(){
      this.data.farmsDetail&&this.data.farmsDetail.forEach((aFarmDetail)=>{
      if(aFarmDetail.isWarning==true)this.deleteSelectedFarmDetail(aFarmDetail.id,this.data.companyDetail.id)
    })
    this.data.farmsDetail&&this.data.farmsDetail.forEach((aFarmDetail)=>{
      if(aFarmDetail.isChanged)this.putAFarmDetail(aFarmDetail)}) 
  },
  deleteSelectedFarmDetail(farmId,companyId){
    //TODO:删除农场的接口
    http.delRequest(
      `/admin/farm/${farmId}/${companyId}`,
      null,
      (success)=>{
        console.log(success)
      },
      (error)=>{

      }
    )
  },

  //如果不为空返回false，否则返回true，并提示用户
  //TODO:添加默认图片
  isEmptyCompanyDetail(data) {
    if (this.data.phoneStatus == 'error') {
      wx.showToast({
        title: '电话号码有误',
        icon: 'error'
      })
      return true
    }
    for (let i in this.data.inputConfig) {
      if (!(i == 'pictures' || i == 'introduction') && (data[i] == '' || data[i] == undefined)) {
        wx.showToast({
          title: this.data.inputConfig[i] + "不能为空",
          icon: 'error'
        })
        return true
      }
      // else if(i == 'pictures'&&data[i] == '' || data[i] == undefined)//TODO:添加默认图片
      // {
      //   this.setData({
      //     companyDetail:{...this.data.companyDetail,pictures:["https://traceability-1258993064.cos.ap-guangzhou.myqcloud.com/clipboard_20230713_120947.png","https://traceability-1258993064.cos.ap-guangzhou.myqcloud.com/clipboard_20230713_121041.png"]}
      // })
      // }
    }
  },
  changePageState() {
    if (this.data.pageState == 1) {
      this.setData({
        pageState: 0,
        pageTitle: pageTitleList[0]
      })
    }
    this.setData({
      isEdit: !this.data.isEdit,
    })
  },
  /**
   * 请求函数
   */
  // 修改CompanyDetail
  async getCompanyDetail(companyId) {
    return new Promise((resolve, reject) => {
      http.getRequest(
        // TODO:暂定用分页查询代替查询全部,数据量多后可能出现获取的公司不足
        "/admin/company/" + companyId,
        {},
        async (res) => {
          this.setData({
            companyDetail: res.data.data
          })
          resolve();
        },
        (err) => {
          wx.navigateBack()
          wx.showToast({
            title: '获取信息失败',
            icon: 'error',
            success: function () {
            }
          })
          reject(err); // 失败时拒绝 Promise
        });
    })
  },
  /**
   * 
   * @param {Array<Object>} CompanyDetail this.data.CompanyDetail
   * @param {Array<Object>} farmsDetail this.data.farmsDetail-<this.tapConfirmOrEdit()>删除的
   */
  putCompanyDetail(companyDetail, farmsDetail) {
    http.putRequest(
      "/admin/company",
      companyDetail,
      (res) => {
        //TODO:同一返回请求
        this.postNewfarms(farmsDetail, companyDetail.id)
        feedback.dealRequestSuccess(
          res,
          '更新成功',
          ()=>{this.onLoad({id:this.data.companyDetail.id})},
          '更新失败',
          ()=>{this.onLoad({id:this.data.companyDetail.id})}
          )
      },
      (err) => {
        wx.showModal({
          title: '更改失败',
          content: '请稍后重试',
          complete: (res) => {
          }
        })
      }
    )
  },
  /**
   * <this.putCompanyDetail()>post需新增加的农场
   * @param {Array<Object>} farmsDetail this.data.farmsDetail
   * @param {Int} companyId this.data.companyDetail.id
   * 
   */
  postNewfarms(farmsDetail, companyId) {
    farmsDetail||farmsDetail.map((afarmDetail) => {
      if (afarmDetail.id == -1) {
         this.postAFarmDetail(afarmDetail, companyId)
      }
    })
  },
  AddCompanyIdToAFarmDetail(AFarmDetail, companyId) {
    AFarmDetail.companyId = companyId
    return AFarmDetail
  },
  /**
   * @private post
   * @param {Object} AFarmDetail 
   * @param {Int} companyId 
   * @return {boolean} true:业务成功；false：失败+业务失败
   */
  async postAFarmDetail(AFarmDetail, companyId) {
    feedback.showLoading()
    AFarmDetail = this.AddCompanyIdToAFarmDetail(AFarmDetail, companyId)
    http.postRequestBody(
      "/admin/farm",
      AFarmDetail,
      (res) => {
        if(!feedback.ifRequestSuccess)feedback.showISee(`添加${AFarmDetail.farmName}失败`)
      },
      (err) => {
        feedback.showISee(`添加${AFarmDetail.farmName}失败`)
      }
    );
  },

  /**
   * 
   * @param {Object} AFarmDetail this.data.farmsDetail<AFarmDetail>
   */
  putAFarmDetail(AFarmDetail){
    http.putRequest(
      "/admin/farm",
      AFarmDetail,
      (res) => {
        typeof(res.data.success)==='boolean'&&res.data.success===false&&feedback.showISee(`${AFarmDetail.farmName}:`+res.data.message)
      },
      (err) => {
        feedback.showISee('添加失败')
      }
    );
  },

  /**
   * 
   * @param {Array<Object>} companyDetail this.data.companyDetail
   * @param {Array<Object>} farmsDetail this.data.farmsDetail-删除的<this.tapConfirmOrEdit()>
   */
  postCompanyDetail(companyDetail, farmsDetail) {
    companyDetail.farms = farmsDetail
    feedback.showLoading()
    http.postRequestBody(
      "/admin/company",
      companyDetail,
      (res) => {
        wx.navigateBack({
          delta:1,
          success:()=>{
            feedback.dealRequestSuccess(res,'新增成功',null,'新增失败',null)
          }
        })
      },
      (err) => {
        feedback.showISee(err.message)
      }
    );
  },
  /**
   * 
   * 上传图片组件中，上传图片的功能函数
   * @param {String} pictureurl 
   * @param {int} index pictureNo of uploadPictureFiles
   */
  postPicture(pictureurl, index) {
    const task = wx.uploadFile({
      url: "https://37y5825u15.oicp.vip" + '/admin/cos/upload',
      filePath: pictureurl,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        if (this.data.isEdit) {
          this.setData({
            [`uploadPictureFiles[${index}].status`]: 'done',
            [`uploadPictureFiles[${index}].url`]: JSON.parse(res.data).data,
            [`companyDetail.pictures`]: this.data.companyDetail.pictures ? [...this.data.companyDetail.pictures, JSON.parse(res.data).data] : [JSON.parse(res.data).data]
          });
        }
      },
      fail: (res) => {
        if (this.data.isEdit) {
          wx.showToast({
            title: '图片上传失败',
            icon: 'error'
          })
          this.setData({
            [`uploadPictureFiles[${index}].status`]: 'failed',
          });
        }
      }
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`uploadPictureFiles[${index}].percent`]: res.progress,
        [`uploadPictureFiles[${index}].status`]: 'loading',
      });
    });
  },
  /**
   * 校验函数
   */
  ifPhoneNumber(phone) {
    const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
    if (phone.length == 0) {
      this.setData({
        phoneStatus: 'error',
        phoneErrorInfo: '手机号长度不能为0'
      })
    } else if (phone.length !== 11) {
      this.setData({
        phoneStatus: 'error',
        phoneErrorInfo: '手机长度有误'
      })
    }
    else if (!reg.test(phone)) {
      this.setData({
        phoneStatus: 'error',
        phoneErrorInfo: '手机号格式有误'
      })
    } else {
      this.setData({
        phoneStatus: 'success',
        phoneErrorInfo: ''
      })
      return true
    }
    return false
  },
  inputCompanyDetail(event) {
    if (event.target.id == 'phone' && this.ifPhoneNumber(event.detail.value) == true) {
      this.setData({
        companyDetail: { ...this.data.companyDetail, [event.target.id]: event.detail.value }
      })
    } else {
      this.setData({
        companyDetail: { ...this.data.companyDetail, [event.target.id]: event.detail.value }
      })
    }
    //TODO:删除图片
  },
  inputFarmsDetail(event) {
    this.setData({
      popupFarmsDetail: { ...this.data.popupFarmsDetail, [event.currentTarget.id]: event.detail.value }
    })
  },
  change() {
    wx: wx.navigateTo({
      url: '/pages/companyInformation/change/change',
      events: false,
      success: (result) => { },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  deleteshow() {
    let is = !this.data.isdelete
    this.setData({
      isdelete: is,
    })
  },
  async getFarmsData(farmIds) {
    http.getRequest(
      // TODO:暂定用分页查询代替查询全部,数据量多后可能出现获取的公司不足
      "/admin/company/" + farmIds + "/farm",
      {},
      (res) => {
        this.setData({
          farmsDetail: res.data.data
        })
      },
      (err) => { }
    )
  },

  /**
   * @public t-upload 图片上传组件
   */
  addPicture(e) {
    const { files } = e.detail;
    this.postPicture(files[files.length - 1].url, this.data.uploadPictureFiles.length)
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.setData({
      uploadPictureFiles: files,
    });
  },
  handleRemove(e) {
    console.log(e)
    const { index } = e.detail;
    const { uploadPictureFiles } = this.data;
    let companyPictures = this.data.companyDetail.pictures.splice(index, 1)
    uploadPictureFiles.splice(index, 1);
    this.setData({
      uploadPictureFiles,
      companyDetail: { ...this.data.companyDetail, pictures: companyPictures }
    });
  },
  handleClick(e) {
    // console.log(e.detail.file);
  },
  /**
   * @private
   * @param {array<pictureUrl>} pictures
   */
  pushToUploadPictureFiles(pictures) {
    const result = this.data.uploadPictureFiles
    for (let i in pictures) {
      result.push({
        url: pictures[i],
        name: 'uploaded1.png',
        type: 'image',
      })
    }
    this.setData({
      uploadPictureFiles: result
    })
  },
  /**
   * @public 点击删除农场按钮
   */
  tapDeleteFarmDetail(e) {
    this.setData({
      [`farmsDetail[${e.currentTarget.dataset.index}].isWarning`]:!this.data.farmsDetail[e.currentTarget.dataset.index].isWarning 
    })
    // this.setData({
    //   [`companyDetail.farmIds`]:this.data.companyDetail.farmIds.filter(id => id !== this.data.farmsDetail[e.currentTarget.dataset.index].id)
    // })

    // TODO:删除相关农场
  },
  /**
   * 弹出层
   */
  showFarmPopup(event) {
    if (this.data.isEdit == true) {
      this.changePopupVisible()
      if (event.currentTarget.id == "farm-card-addButton") {
        this.changePopupFarmsDetail(-1)
      } else {
        this.getIdFromTagId(event.currentTarget.id) && this.changePopupFarmsDetail(this.getIdFromTagId(event.currentTarget.id));
      }
    }
  },
  /**
   * 
   * @param {String} result 从字符串末尾（盒子的id）提取是第几个农场
   */
  getIdFromTagId(result) {
    return result.match(/\d+$/)[0]
  },
  confirmPopup(event) {
    if (this.data.cascaderCellNote != '' && this.data.popupFarmsDetail['farmName']) {
      const result = this.data.farmsDetail ? this.data.farmsDetail : [] //判断detail是否为空
      this.data.popupFarmsIndex == -1 ? result.push({ ...this.data.popupFarmsDetail, supplyFarmAddress: this.data.cascaderCellNote }) : result[this.data.popupFarmsIndex] = { ...this.data.popupFarmsDetail, supplyFarmAddress: this.data.cascaderCellNote,isChanged:true } //是新增农场还是修改农场信息
      this.setData({
        farmsDetail: result,
        cascaderCellNote: ''
      })
      this.changePopupVisible()
    } else {
      wx.showToast({
        title: '信息未填写完毕',
        icon: 'error'
      })
    }
  },
  updataFarmsDetail(getNewData) {
    const newData = getNewData()
    this.setData({
      farmsDetail: newData
    })
  },
  changePopupVisible() {
    this.setData({
      popupVisible: !this.data.popupVisible,
    });
  },
  //id==-1:清空；否则通过id从this.data获取对应农场信息
  changePopupFarmsDetail(id) {
    if (id == -1) {
      this.setData({
        popupFarmsDetail: {
          id: '-1',
          farmName: '',
          supplyFarmAddress: '',
        },
        cascaderCellNote: '',
        popupFarmsIndex: id
      });
    } else if (id >= 0) {
      this.setData({
        popupFarmsDetail: this.data.farmsDetail[id],
        cascaderCellNote: this.data.farmsDetail[id].supplyFarmAddress,
        popupFarmsIndex: id
      });
    }
  },
  onVisibleChange(e) {
    this.setData({
      popupVisible: e.detail.visible,
    });
  },
  /**
   * 地址选择
   */
  showCascader() {
    this.setData({ cascaderVisible: true });
  },
  onPick(e) {
    // console.log(e.detail);//选择的信息
  },
  onChange(e) {
    const { selectedOptions, cascaderValue } = e.detail;
    this.setData({
      cascaderValue,
      cascaderCellNote: selectedOptions.map((item) => item.label).join('/'),
    });
  },
  updataFarmAddress(event) {
    //地址先存放到this.data.cascaderCellNote，点击确定的时候再放到farmsDetail
  },

  /**
   * @private 
   * initialize data of page, get CompanyDetail & FarmsData & ...
   */
  async initPageData(id) {
    this.getCompanyDetail(id).then(
      () => {
        this.setData({
          uploadPictureFiles: []
        })
        if(!this.data.companyDetail.pictures)this.pushToUploadPictureFiles(this.data.companyDetail.pictures)
      }
    )
    this.getFarmsData(id)
  },
  /**
   * @private
   * @param {0,1} init pageState & isEdit
   */
  initPageState(pageState) {
    this.setData({
      pageState: pageState,
      pageTitle: pageTitleList[pageState],
      isEdit: pageState == 0 ? false : true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   * @param {int} options.id options.id == -1:新增公司
   */
  onLoad(options) {
    if (options.id == -1) { // 新增公司
      this.initPageState(1)
    } else {
      this.initPageState(0)
      this.initPageData(options.id)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})